package model

import (
	"time"

	"github.com/pkg/errors"
	"gorm.io/gorm"
)

type Project struct {
	ID        uint      `gorm:"primaryKey;autoIncrement" json:"id"`
	CreatedAt time.Time `gorm:"column:created_at" json:"created_at"`
	UpdatedAt time.Time `gorm:"column:updated_at" json:"updated_at"`
	Name      string    `gorm:"size:64;not null;unique;column:name" json:"name"`
	Introduce string    `gorm:"size:255;not null;column:introduce" json:"introduce"`
	TeamID    uint      `gorm:"not null;column:team_id" json:"team_id"`
	CreateBy  string    `gorm:"column:create_by;type:varchar(64)" json:"create_by"` // 创建者
}

func (p *Project) Create(tx *gorm.DB) (uint, error) {
	// 如果id为0，则创建
	if p.ID == 0 {
		result := tx.Create(p)
		if result.Error != nil {
			return 0, errors.New("创建项目失败")
		}
	} else {
		result := tx.Save(p)
		if result.Error != nil {
			return 0, errors.New("更新项目失败")
		}
	}
	return p.ID, nil
}

func (p *Project) Delete(tx *gorm.DB) error {
	if err := tx.Model(p).Delete(p).Error; err != nil {
		return errors.New("删除项目失败")
	}
	return nil
}

func (p *Project) GetByID(tx *gorm.DB, id any) (*Project, error) {
	result := tx.Model(p).First(p, id)
	if result.Error != nil || errors.Is(result.Error, gorm.ErrRecordNotFound) {
		return nil, errors.New("获取项目失败")
	}
	return p, nil
}

func (p *Project) List(tx *gorm.DB, page, pageSize int) ([]*Project, error) {
	var projects []*Project

	m := tx.Model(p)
	if p.TeamID != 0 {
		m = m.Where("team_id = ?", p.TeamID)
	}
	result := m.Offset((page - 1) * pageSize).Limit(pageSize).Find(&projects)
	if result.Error != nil || errors.Is(result.Error, gorm.ErrRecordNotFound) {
		return nil, errors.New("获取项目列表失败")
	}
	return projects, nil
}
